package org.example.model;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.example.mapper.XpathTest;

import static org.example.domain.ListTable.*;
import static org.example.domain.listforxml.*;

public class xmlreplace {
    public static void replace(String file, String data) {
        try {
            FileInputStream fis = new FileInputStream(file);
            XWPFDocument document = new XWPFDocument(fis);
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                String text = paragraph.getText();
                Pattern pattern1 = Pattern.compile("<var\\s+name=(\\w+)\\s+ds=(.*?)\\s+query=(.*?)>");
                Matcher matcher1 = pattern1.matcher(text);
                Pattern pattern2 = Pattern.compile("<out\\s+var=(\\w+)>");
                Matcher matcher2 = pattern2.matcher(text);
                Pattern pattern3 = Pattern.compile("<foreach>");
                Matcher matcher3 = pattern3.matcher(text);
                Pattern pattern4 = Pattern.compile("<out\\s+var=(\\w+)\\s+foreach>");
                List<String> tablename=new ArrayList<>();
                Pattern pattern11 = Pattern.compile("<out\\s+var=(\\w+) max>");
                Matcher matcher11 = pattern11.matcher(text);
                Pattern pattern12 = Pattern.compile("<out\\s+var=(\\w+) min>");
                Matcher matcher12 = pattern12.matcher(text);
                Pattern pattern13 = Pattern.compile("<out\\s+var=(\\w+) count>");
                Matcher matcher13 = pattern13.matcher(text);
                Pattern pattern14 = Pattern.compile("<out\\s+var=(\\w+) sum>");
                Matcher matcher14 = pattern14.matcher(text);
                Pattern pattern15 = Pattern.compile("<out\\s+var=(\\w+) avg>");
                Matcher matcher15 = pattern15.matcher(text);

                if (matcher1.find()) {
                    String name = matcher1.group(1); // 获取第一个括号中匹配的内容，即 name
                    String ds = matcher1.group(2);   // 获取第二个括号中匹配的内容，即 ds
                    String query = matcher1.group(3);
                    xmlvarlist.add(name);
                    xmldatasourcelist.add(ds);
                    xmlquerylist.add(query);
                    xmlhashTable.put(name, XpathTest.insertxml(data,query));
                    //除去指令
                    text=text.replaceAll("<var\\s+name=(\\w+)\\s+ds=(.*?)\\s+query=(.*?)>","");
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }
                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);

                }
                if(matcher2.find()){
                    String name = matcher2.group(1);
                    if (xmlvarlist.contains(name)){
                        text = text.replaceAll("<out\\s+var=(\\w+)>",xmlhashTable.get(name).toString());
                        System.out.println("有" + text);
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher11.find()){
                    String name = matcher11.group(1);
                    if (xmlvarlist.contains(name)){
                        List<Double> list = xmlhashTable.get(name).stream()
                                .map(Double::parseDouble) // 将每个字符串转换为double
                                .collect(Collectors.toList());

                    double max = -100000; // 初始化

                    for (Double number:list) {
                        if (number > max) {
                            max = number;
                        }
                    }

                    text = text.replaceAll("<out\\s+var=(\\w+) max>", max+"");
                    System.out.println("有" + text);
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher12.find()){
                    String name = matcher12.group(1);
                    if (xmlvarlist.contains(name)){
                        List<Double> list = xmlhashTable.get(name).stream()
                                .map(Double::parseDouble) // 将每个字符串转换为double
                                .collect(Collectors.toList());

                        double min = 100000; // 初始化

                        for (Double number:list) {
                            if (number < min) {
                                min = number;
                            }
                        }

                        text = text.replaceAll("<out\\s+var=(\\w+) min>", min+"");
                        System.out.println("有" + text);
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher13.find()){
                    String name = matcher13.group(1);
                    if (xmlvarlist.contains(name)){
                        List<Double> list = xmlhashTable.get(name).stream()
                                .map(Double::parseDouble) // 将每个字符串转换为double
                                .collect(Collectors.toList());

                        Set<?> set = new HashSet<>(list);
                        text = text.replaceAll("<out\\s+var=(\\w+) count>", set.size()+"");
                        System.out.println("有" + text);
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher14.find()){
                    String name = matcher14.group(1);
                    if (xmlvarlist.contains(name)){
                        List<Double> list = xmlhashTable.get(name).stream()
                                .map(Double::parseDouble) // 将每个字符串转换为double
                                .collect(Collectors.toList());
                        double sum = 0; // 初始化为可能的最小值

                        for (Double number:list) {
                            sum+=number;
                        }

                        text = text.replaceAll("<out\\s+var=(\\w+) sum>", sum+"");
                        System.out.println("有" + text);
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher15.find()){
                    String name = matcher15.group(1);
                    if (xmlvarlist.contains(name)){
                        List<Double> list = xmlhashTable.get(name).stream()
                                .map(Double::parseDouble) // 将每个字符串转换为double
                                .collect(Collectors.toList());
                        double avg = 0; // 初始化为可能的最小值

                        for (Double number:list) {
                            avg+=number;
                        }

                        text = text.replaceAll("<out\\s+var=(\\w+) avg>", avg/list.size()+"");
                        System.out.println("有" + text);
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }


                if(matcher3.find()){
                    for (XWPFTable table : document.getTables()) {
                        for (int i = 0; i < table.getNumberOfRows(); i++) {
                            for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
                                // 获取单元格中的所有段落
                                for (XWPFParagraph paragraph1 : table.getRow(i).getCell(j).getParagraphs()) {
                                    for (XWPFRun run : paragraph1.getRuns()) {
                                        // 检查是否包含文本"a"
                                        Matcher m4= pattern4.matcher(run.text());
                                        if (m4.find()) {
                                            String name= m4.group(1);
                                            tablename.add(name);
                                            System.out.println(name+"Found at row " + i + ", column " + j);
                                            int[]temp={i,j};
                                            xmltablenameindex.put(name,temp);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    boolean flag=true;
                    int[]a=new int[tablename.size()];
                    int num=0;
                    for(String str:tablename){
                        List<String>list=xmlhashTable.get(str);
                        a[index]=list.size();
                        num=a[0];
                        xmlindexlist.put(str,list);
                        index++;

                    }


                    for(int j=1;j< tablename.size();j++){
                        if(a[j]!=a[0]){
                            System.out.println("不匹配");
                            flag=false;

                        }

                    }
                    if(flag==true){
                        for(int j=0;j<num;j++){
                            XWPFTable originalTable = document.getTables().get(0);
                            XWPFTable newTable = document.createTable(0,0);

                            for (XWPFTableRow row : originalTable.getRows()) {
                                XWPFTableRow newRow = newTable.createRow();
                                newRow.setHeight(200);

                                for (XWPFTableCell cell : row.getTableCells()) {
                                    XWPFTableCell newCell = newRow.createCell();
                                    TableWidthType type=cell.getWidthType();
                                    newCell.setWidth("2000");


                                    for (XWPFParagraph paragraph1 : cell.getParagraphs()) {
                                        XWPFParagraph newParagraph = newCell.addParagraph();
                                        for (XWPFRun run : paragraph1.getRuns()) {
                                            XWPFRun newRun = newParagraph.createRun();
                                            newRun.setText(run.getText(0));
                                        }
                                    }
                                }
                            }


                            for(int x=0;x< tablename.size();x++){
                                newTable.getRow(xmltablenameindex.get(tablename.get(x))[0]+1).getCell(xmltablenameindex.get(tablename.get(x))[1]+1).removeParagraph(0);

                                newTable.getRow(xmltablenameindex.get(tablename.get(x))[0]+1).getCell(xmltablenameindex.get(tablename.get(x))[1]+1).setText(xmlindexlist.get(tablename.get(x)).get(j));
                                System.out.println(xmlindexlist.get(tablename.get(x)).get(j));

                            }
                            for (XWPFTableRow row : newTable.getRows()) {
                                // 移除每行的第一列
                                row.removeCell(0);
                            }
                        }
                    }

                }



                for (XWPFTable table : document.getTables()) {
                    for (XWPFTableRow row : table.getRows()) {
                        for (int i = 0; i < row.getTableCells().size(); i++) {
                            String cellText = row.getCell(i).getText();
                            Pattern patternaa = Pattern.compile("<out\\s+var=(\\w+)>");
                            Matcher matcheraa = patternaa.matcher(cellText);
                            Pattern pattern111 = Pattern.compile("<out\\s+var=(\\w+) max>");
                            Matcher matcher111 = pattern111.matcher(cellText);
                            Pattern pattern112 = Pattern.compile("<out\\s+var=(\\w+) min>");
                            Matcher matcher112 = pattern112.matcher(cellText);
                            Pattern pattern113 = Pattern.compile("<out\\s+var=(\\w+) count>");
                            Matcher matcher113 = pattern113.matcher(cellText);
                            Pattern pattern114 = Pattern.compile("<out\\s+var=(\\w+) sum>");
                            Matcher matcher114 = pattern114.matcher(cellText);
                            Pattern pattern115 = Pattern.compile("<out\\s+var=(\\w+) avg>");
                            Matcher matcher115 = pattern115.matcher(cellText);
                            if (matcheraa.find()) {
                                String name = matcheraa.group(1);
                                if (xmlvarlist.contains(name)){
                                    cellText = cellText.replaceAll("<out\\s+var=(\\w+)>",xmlhashTable.get(name).toString());
                                    System.out.println("表格中有" + cellText);
                                }
                                row.getCell(i).removeParagraph(0);

                                row.getCell(i).setText(cellText);
                            }

                            if(matcher111.find()){
                                String name = matcher111.group(1);
                                if (xmlvarlist.contains(name)){
                                    List<Double> list = xmlhashTable.get(name).stream()
                                            .map(Double::parseDouble) // 将每个字符串转换为double
                                            .collect(Collectors.toList());

                                    double max = -100000; // 初始化

                                    for (Double number:list) {
                                        if (number > max) {
                                            max = number;
                                        }
                                    }

                                    cellText = cellText.replaceAll("<out\\s+var=(\\w+) max>", max+"");
                                    System.out.println("有" + cellText);
                                }
                                row.getCell(i).removeParagraph(0);

                                row.getCell(i).setText(cellText);
                            }
                            if(matcher112.find()){
                                String name = matcher112.group(1);
                                if (xmlvarlist.contains(name)){
                                    List<Double> list = xmlhashTable.get(name).stream()
                                            .map(Double::parseDouble) // 将每个字符串转换为double
                                            .collect(Collectors.toList());

                                    double min = 100000; // 初始化

                                    for (Double number:list) {
                                        if (number < min) {
                                            min = number;
                                        }
                                    }

                                    cellText =cellText.replaceAll("<out\\s+var=(\\w+) min>", min+"");
                                    System.out.println("有" + cellText);
                                }
                                row.getCell(i).removeParagraph(0);

                                row.getCell(i).setText(cellText);
                            }
                            if(matcher113.find()){
                                String name = matcher113.group(1);
                                if (xmlvarlist.contains(name)){
                                    List<Double> list = xmlhashTable.get(name).stream()
                                            .map(Double::parseDouble) // 将每个字符串转换为double
                                            .collect(Collectors.toList());

                                    Set<?> set = new HashSet<>(list);
                                    cellText = cellText.replaceAll("<out\\s+var=(\\w+) count>", set.size()+"");
                                    System.out.println("有" + cellText);
                                }
                                row.getCell(i).removeParagraph(0);

                                row.getCell(i).setText(cellText);
                            }
                            if(matcher114.find()){
                                String name = matcher114.group(1);
                                if (xmlvarlist.contains(name)){
                                    List<Double> list = xmlhashTable.get(name).stream()
                                            .map(Double::parseDouble) // 将每个字符串转换为double
                                            .collect(Collectors.toList());
                                    double sum = 0; // 初始化为可能的最小值

                                    for (Double number:list) {
                                        sum+=number;
                                    }

                                    cellText = cellText.replaceAll("<out\\s+var=(\\w+) sum>", sum+"");
                                    System.out.println("有" + cellText);
                                }
                                row.getCell(i).removeParagraph(0);

                                row.getCell(i).setText(cellText);
                            }
                            if(matcher115.find()){
                                String name = matcher115.group(1);
                                if (xmlvarlist.contains(name)){
                                    List<Double> list = xmlhashTable.get(name).stream()
                                            .map(Double::parseDouble) // 将每个字符串转换为double
                                            .collect(Collectors.toList());
                                    double avg = 0; // 初始化为可能的最小值

                                    for (Double number:list) {
                                        avg+=number;
                                    }

                                    cellText = cellText.replaceAll("<out\\s+var=(\\w+) avg>", avg/list.size()+"");
                                    System.out.println("有" + cellText);
                                }
                                row.getCell(i).removeParagraph(0);

                                row.getCell(i).setText(cellText);
                            }

                        }
                    }
                }

            }

            List<xmlreplace.TableCell> cellsToExpand = new ArrayList<>();
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        // 检查单元格中的段落是否包含"<out var=a expand>"
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            String text = paragraph.getText();
                            Pattern patternExpand = Pattern.compile("\\<out\\s+var=(\\w+)\\s+expand\\>");
                            Matcher matcherExpand = patternExpand.matcher(text);
                            if (matcherExpand.find()) {
                                String varName = matcherExpand.group(1);
                                if (xmlhashTable.containsKey(varName)) {
                                    // 记录需要扩展的单元格
                                    cellsToExpand.add(new xmlreplace.TableCell(table, row, cell,varName));
                                }
                            }
                        }
                    }
                }
            }

            // 根据记录的位置信息，进行单元格的扩展
            for (xmlreplace.TableCell cellToExpand : cellsToExpand) {
                XWPFTableCell cell = cellToExpand.getCell();
                XWPFTableRow row = cellToExpand.getRow();
                String varName = cellToExpand.getVarName();

                Object varValue = xmlhashTable.get(varName);
                if (varValue instanceof List) {
                    List<?> list = (List<?>) varValue;
                    // 创建与列表长度相等的行
                    for (int i = 0; i < list.size(); i++) {

                        XWPFTableCell newCell = row.createCell();
                        newCell.setText(list.get(i).toString());

                    }
                }
            }


            //检验结果
            for(String str:xmlvarlist){
                System.out.println(str);

            }
            System.out.println("--------------");
            for(String str:xmldatasourcelist){
                System.out.println(str);
            }
            System.out.println("--------------");
            for(String str: xmlhashTable.keySet()){
                System.out.println(xmlhashTable.get(str));
            }

            FileOutputStream out=new FileOutputStream("output.docx");
            document.write(out);
            document.close();
            fis.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    private static class TableCell {
        private final XWPFTable table;
        private final XWPFTableRow row;
        private final XWPFTableCell cell;
        private final String varName;

        public TableCell(XWPFTable table, XWPFTableRow row, XWPFTableCell cell,String varName) {
            this.table = table;
            this.row = row;
            this.cell = cell;
            // 这里需要根据实际情况获取变量名
            this.varName = varName;
        }

        public XWPFTable getTable() {
            return table;
        }

        public XWPFTableRow getRow() {
            return row;
        }

        public XWPFTableCell getCell() {
            return cell;
        }

        public String getVarName() {
            return varName;
        }
    }

}
